<?php
/**
 * 退款
 * @author jy625
 */

namespace Weixinpay;
use app\common\model\Agent;
use app\common\model\WxOpen;

class Wxtk
{
    private $parameters; //cft 参数
    private $wx_open_id;

    function __construct($options)
    {
        $this->wx_open_id = isset($options['wx_open_id']) ? $options['wx_open_id'] : '';
    }

    //设置参数
    function setParameter($parameter, $parameterValue)
    {
        $this->parameters [CommonUtil::trimString($parameter)] = CommonUtil::trimString($parameterValue);
    }

    //获取参数
    function getParameter($parameter)
    {
        return $this->parameters [$parameter];
    }
    function setwxopenid($parameter)
    {

    }
    //检查签名参数
    function check_sign_parameters()
    {
        if (
            $this->parameters["appid"] == null ||
            $this->parameters["mch_id"] == null ||
            $this->parameters["sub_mch_id"] == null ||
            $this->parameters["nonce_str"] == null ||
            $this->parameters["refund_desc"] == null ||
            $this->parameters["out_trade_no"] == null ||
            $this->parameters["out_refund_no"] == null ||
            $this->parameters["total_fee"] == null ||
            $this->parameters["refund_fee"] == null
        ) {
            return false;
        }
        return true;

    }
    /**
     * 例如：
     * appid：    wxd111665abv58f4f
     * mch_id：    10000100
     * device_info：  1000
     * Body：    test
     * nonce_str：  ibuaiVcKdpRxkhJA
     * 第一步：对参数按照 key=value 的格式，并按照参数名 ASCII 字典序排序如下：
     * stringA="appid=wxd930ea5d5a258f4f&body=test&device_info=1000&mch_i
     * d=10000100&nonce_str=ibuaiVcKdpRxkhJA";
     * 第二步：拼接支付密钥：
     * stringSignTemp="stringA&key=192006250b4c09247ec02edce69f6a2d"
     * sign=MD5(stringSignTemp).toUpperCase()="9A0A8659F005D6984697E2CA0A
     * 9CF3B7"
     */
    //签名
    protected function get_sign($api_key)
    {

        $commonUtil = new CommonUtil ();
        ksort($this->parameters);
        $unSignParaString = $commonUtil->formatQueryParaMap($this->parameters, false);

        $md5SignUtil = new MD5SignUtil ();
        return $md5SignUtil->sign($unSignParaString, $commonUtil->trimString($api_key));
    }
    protected function get_sign_hash($api_key)
    {

        $commonUtil = new CommonUtil ();
        ksort($this->parameters);
        $unSignParaString = $commonUtil->formatQueryParaMap($this->parameters, false);
        $md5SignUtil = new MD5SignUtil ();
        return $md5SignUtil->sign_hash($unSignParaString, $commonUtil->trimString($api_key));
    }
    /*
    <xml>
        <sign>![CDATA[E1EE61A9]]</sign>
        <mch_billno>![CDATA[00100]]</mch_billno>
        <mch_id>![CDATA[888]]</mch_id>
        <wxappid>![CDATA[wxcbda96de0b165486]]</wxappid>
        <nick_name>![CDATA[nick_name]]</nick_name>
        <send_name>![CDATA[send_name]]</send_name>
        <re_openid>![CDATA[onqOjjXXXXXXXXX]]</re_openid>
        <total_amount>![CDATA[100]]</total_amount>
        <min_value>![CDATA[100]]</min_value>
        <max_value>![CDATA[100]]</max_value>
        <total_num>![CDATA[1]]</total_num>
        <wishing>![CDATA[恭喜发财]]</wishing>
        <client_ip>![CDATA[127.0.0.1]]</client_ip>
        <act_name>![CDATA[新年红包]]</act_name>
        <act_id>![CDATA[act_id]]</act_id>
        <remark>![CDATA[新年红包]]</remark>
    </xml>
    */
    //退款
    function create_refund_xml($api_key)
    {
        try {
            $this->setParameter('sign', $this->get_sign($api_key));
            $commonUtil = new CommonUtil ();
            return $commonUtil->arrayToXml($this->parameters);

        } catch (SDKRuntimeException $e) {
            die ($e->errorMessage());
        }
    }
    function create_fz_xml($api_key)
    {
        try {
//            return hash_hmac('sha256',123,321);
//            return $this->get_sign_hash($api_key);
            $this->setParameter('sign', $this->get_sign_hash($api_key));
            $commonUtil = new CommonUtil ();
            return $commonUtil->arrayToXml2($this->parameters);

        } catch (SDKRuntimeException $e) {
            die ($e->errorMessage());
        }
    }
    //提交请求
    function curl_post_ssl($url, $vars, $second = 30, $aHeader = array())
    {
        $Agent=new Agent();
        $info=$Agent->where(['wx_open_id'=>$this->wx_open_id])->find();
//file_put_contents('/data2/html/payos/test.txt',json_encode($info),8);
        $apiclient_cert=$info['apiclient_cert'];
        $apiclient_key=$info['apiclient_key'];
        $rootca=$info['rootca'];

        $ch = curl_init();
        //超时时间
        curl_setopt($ch, CURLOPT_TIMEOUT, $second);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        //这里设置代理，如果有的话
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

        //cert 与 key 分别属于两个.pem文件
        curl_setopt($ch, CURLOPT_SSLCERT, $apiclient_cert);
        curl_setopt($ch, CURLOPT_SSLKEY, $apiclient_key);
        curl_setopt($ch, CURLOPT_CAINFO, $rootca);

        if (count($aHeader) >= 1) {
            curl_setopt($ch, CURLOPT_HTTPHEADER, $aHeader);
        }

        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $vars);
        $data = curl_exec($ch);
        if ($data) {
            curl_close($ch);
            return $data;
        } else {
            $error = curl_errno($ch);
            curl_close($ch);
            return false;
        }
    }

    public function generateNonceStr($length = 16)
    {
        // 密码字符集，可任意添加你需要的字符
        $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        $str = "";
        for ($i = 0; $i < $length; $i++) {
            $str .= $chars[mt_rand(0, strlen($chars) - 1)];
        }
        return $str;
    }

    public function getmercode($code)
    {
        $err_code = array(
            'OK'=>'操作成功',
            'SYSTEMERROR' => '接口返回错误',
            'BIZERR_NEED_RETRY' => '退款业务流程错误，需要商户触发重试来解决',
            'TRADE_OVERDUE	订单已经超过退款期限',
            'ERROR	业务错误',
            'USER_ACCOUNT_ABNORMAL	退款请求失败',
            'INVALID_REQ_TOO_MUCH	无效请求过多',
            'NOTENOUGH	余额不足',
            'INVALID_TRANSACTIONID' => '无效transaction_id',
            'PARAM_ERROR' => '参数错误 ',
            'APPID_NOT_EXIST' => 'APPID不存在 ',
            'MCHID_NOT_EXIST' => 'MCHID不存在 ',
            'REQUIRE_POST_METHOD' => '请使用post方法',
            'SIGNERROR' => '签名错误',
            'XML_FORMAT_ERROR' => 'XML格式错误 ',
            'FREQUENCY_LIMITED' => '频率限制');
        return $err_code[$code];
    }
}

?>